package com.zprmb.udzt.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zprmb.udzt.BaseActivity;
import com.zprmb.udzt.BbtApplication;
import com.zprmb.udzt.R;
import com.zprmb.udzt.V6DetailsActivity;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.view.WebViewDialog;




@SuppressLint("SetJavaScriptEnabled")
public class ProjectDetail_QuestionActivity extends BaseActivity implements OnClickListener {

    private ImageView iv_v4_web_back;
    private TextView tv_v4_web_title;
    private String title;

    private String url;
    private boolean isOnPause = false;

    String version = "";
    private WebView v4_webview;
    private static final String SHARE = "um";
    private RelativeLayout rl_back;
    //	private ProgressBar bar;
    private boolean back = false;
    private WebViewDialog dialog;

    private View web_head_view;
    private View title_view;
    private ImageView iv_v4_nonetwork;


    //banner的webview
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_projectdetail);
        setImmersionStatus();
//		Toast.makeText(this, "第二页", Toast.LENGTH_SHORT).show();
        BbtApplication.getInstance().addActvity(this);

        Intent intent = getIntent();
        dialog = new WebViewDialog(this);
        title = "详情";
        url = intent.getStringExtra("url");
        version = getAppVersion();
        LogUtils.e(ProjectDetail_QuestionActivity.this, url);
        iv_v4_nonetwork = (ImageView) findViewById(R.id.iv_v4_nonetwork);
        v4_webview = (WebView) findViewById(R.id.v4_webview);
        initView();

        v4_webview.loadUrl(url);


        v4_webview.resumeTimers();

        if (!network()) {
            iv_v4_nonetwork.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    v4_webview = (WebView) findViewById(R.id.v4_webview);
                    iv_v4_nonetwork.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            v4_webview.reload();
                            initData();
                        }
                    });
                }
            });
            iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

            v4_webview.setVisibility(View.GONE);
            title_view.setVisibility(View.VISIBLE);

            web_head_view.setVisibility(View.VISIBLE);
//
        } else {

            iv_v4_nonetwork.setVisibility(View.GONE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

            v4_webview.setVisibility(View.VISIBLE);
            title_view.setVisibility(View.GONE);
            web_head_view.setVisibility(View.VISIBLE);
            initData();
        }


    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        destroyWebView();
        super.onDestroy();

        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
        BbtApplication.getInstance().removeActvity(this);

        handler.removeCallbacksAndMessages(null);
        handler = null;

    }

    private void destroyWebView() {

    }

    @Override
    protected void onPause() {
        super.onPause();

        if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB && url.contains("video")) {
            v4_webview.onPause(); // 暂停网页中正在播放的视频  
        }
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        // TODO Auto-generated method stub
        super.onActivityResult(arg0, arg1, arg2);

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {

   /*         if (v4_webview.canGoBack()) {
                v4_webview.goBack();
            } else {
                finish();
            }
            return true;*/
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            super.onProgressChanged(view, newProgress);
        }
    };
    private boolean loadError = false;

    private void initData() {

        v4_webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//				Log.e("myurl", url+"");
                if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {

                    view.loadUrl(url);
                }

                return true;
            }

            @TargetApi(VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {

                loadError = true;
                iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                v4_webview.setVisibility(View.GONE);
                title_view.setVisibility(View.VISIBLE);

                web_head_view.setVisibility(View.VISIBLE);

            }

            @Override
            public void onReceivedSslError(WebView view,
                                           SslErrorHandler handler, SslError error) {
                // TODO Auto-generated method stub

                handler.proceed();
                loadError = true;
                iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                v4_webview.setVisibility(View.GONE);
                title_view.setVisibility(View.VISIBLE);

                web_head_view.setVisibility(View.VISIBLE);
            }

            @TargetApi(VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                int statusCode = errorResponse.getStatusCode();

                Toast.makeText(ProjectDetail_QuestionActivity.this, statusCode + "", Toast.LENGTH_SHORT).show();

                loadError = true;
                iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                v4_webview.setVisibility(View.GONE);
                title_view.setVisibility(View.VISIBLE);

                web_head_view.setVisibility(View.VISIBLE);
            }

            //			}
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                if (dialog != null & dialog.isShowing() == false) {
                    dialog.show();
                }
                loadError = false;
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub

                // TODO Auto-generated method stub
                try {

                    if (dialog != null & dialog.isShowing() == true) {
                        dialog.dismiss();

                    }
                    if (!loadError) {//当网页加载成功的时候判断是否加载成功
                        iv_v4_nonetwork.setVisibility(View.GONE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView
                        v4_webview.setVisibility(View.VISIBLE);
                        title_view.setVisibility(View.GONE);
                        title_view.setVisibility(View.GONE);

                    } else { //加载失败的话，初始化页面加载失败的图，然后替换正在加载的视图页面

                        iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                        v4_webview.setVisibility(View.GONE);
                        title_view.setVisibility(View.VISIBLE);

                        web_head_view.setVisibility(View.VISIBLE);

                    }
                } catch (Exception e) {

                }


                super.onPageFinished(view, url);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view,
                                                              String url) {
                // TODO Auto-generated method stub
                return super.shouldInterceptRequest(view, url);

            }
        });
        v4_webview.clearCache(true);

        v4_webview.setWebChromeClient(chromeClient);
        // 重新设置websettings WebSettings s = wb.getSettings();
        // s.setBuiltInZoomControls(true);
        // s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setUseWideViewPort(true);

        v4_webview.getSettings().setLoadWithOverviewMode(true);
        v4_webview.getSettings().setSavePassword(true);
        v4_webview.getSettings().setSaveFormData(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        // enable navigator.geolocation
        v4_webview.getSettings().setGeolocationEnabled(true);
        v4_webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");
        // enable Web Storage: localStorage, sessionStorage
//		v4_webview.getSettings().setDomStorageEnabled(true);
        v4_webview.requestFocus();
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4_webview.getSettings().getUserAgentString();
        v4_webview.getSettings().setUserAgentString(
                ua + "; " + "rmbbox_android");
        v4_webview.addJavascriptInterface(new JsInterfaces(this),
                "AndroidWebView");
        v4_webview.getSettings().setBuiltInZoomControls(true);
        v4_webview.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);

        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath();
        try {
            if (VERSION.SDK_INT >= VERSION_CODES.KITKAT_WATCH) {
                v4_webview.getSettings().setMixedContentMode(v4_webview.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
        v4_webview.getSettings().setAllowFileAccess(true);
        v4_webview.getSettings().setAppCacheEnabled(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        v4_webview.getSettings().setAppCachePath(appCachePath);
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4_webview.getSettings().setDefaultTextEncodingName("utf-8");

    }


    private class JsInterfaces {
        private Context mContext;

        public JsInterfaces(Context context) {
            this.mContext = context;
        }


        @JavascriptInterface
        public void showInfoFromJs(String name) {

        }


        @JavascriptInterface
        public void toproduct(String[] list) {

            Intent intent = new Intent(ProjectDetail_QuestionActivity.this,
                    V6DetailsActivity.class);
            intent.putExtra("flag", Boolean.parseBoolean(list[0]));
            intent.putExtra("name", list[1]);
            intent.putExtra("type", list[2]);
            intent.putExtra("id", list[3]);
            intent.putExtra("isred", list[4]);

            startActivity(intent);
        }

        @JavascriptInterface
        public void switchpage(String name) {

        }

    }


    @JavascriptInterface
    public void finish(int type) {

        if (type == 0) {
            ProjectDetail_QuestionActivity.this.finish();
            return;

        }
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                if (v4_webview.canGoBack()) {
                    v4_webview.goBack();
                } else {
                    if (dialog != null) {


                    }
                    Intent intent = new Intent();
                    setResult(1, intent);
                    ProjectDetail_QuestionActivity.this.finish();
                }
            }
        });


    }


    @JavascriptInterface
    public void setTitle(String title) {
        tv_v4_web_title.setText(title);

    }

    @JavascriptInterface
    public void finishActivity() {

        ProjectDetail_QuestionActivity.this.finish();
    }

    @JavascriptInterface
    public void setactivity(String activity) {


        Intent intent;
        try {
            intent = new Intent(ProjectDetail_QuestionActivity.this,
                    Class.forName(activity));
            intent.putExtra("webview", 1);
            startActivity(intent);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @JavascriptInterface
    public void setactivityIntent(String activity, String key, String value) {


        Intent intent;
        try {
            intent = new Intent(ProjectDetail_QuestionActivity.this,
                    Class.forName(activity));
            intent.putExtra("webview", 1);
            intent.putExtra(key, value);
            startActivity(intent);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @JavascriptInterface
    public String getApptoken() {
        return getToken();
    }

    @JavascriptInterface
    public String getAppVersionforM() {

        return version;

    }

    @JavascriptInterface
    public void addmoney() {

    }

    public void sendInfoToJs(View view) {
        String msg = getToken();
//			Log.e("web", "调用");
        // 调用js中的函数：showInfoFromJava(msg)

    }


    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {

                share(ProjectDetail_QuestionActivity.this, msg.getData().getString("description"), msg.getData().getString("title"), msg.getData().getString("sharelink"), msg.getData().getString("imageurl"));
            }


        }

        ;
    };



    private void initView() {
        iv_v4_web_back = (ImageView) findViewById(R.id.img_back);
        rl_back = (RelativeLayout) findViewById(R.id.rl_back);
//		bar = (ProgressBar) findViewById(R.id.myProgressBar);
        title_view = (View) findViewById(R.id.title_view);

        web_head_view = (View) findViewById(R.id.web_head_view);

        if (title.contains("智投宝")) {
            title_view.setVisibility(View.GONE);

        } else {
            if (getIntent().getIntExtra("banner", 0) == 1) {
                title_view.setVisibility(View.GONE);
                web_head_view.setVisibility(View.VISIBLE);
            } else {
                title_view.setVisibility(View.GONE);
                web_head_view.setVisibility(View.GONE);
            }

        }

        rl_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (v4_webview.canGoBack()) {
                    v4_webview.goBack();
                } else {
                    finish();
                }
            }
        });
        iv_v4_web_back.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                if (v4_webview.canGoBack()) {
                    v4_webview.goBack();
                } else {
                    finish();
                }
            }
        });
        tv_v4_web_title = (TextView) findViewById(R.id.tv_title);
        tv_v4_web_title.getPaint().setFakeBoldText(true);
        tv_v4_web_title.setText(title);
        if (title.indexOf("了解") == 0) {
            tv_v4_web_title.setText("项目详情");
        } else {

            tv_v4_web_title.setText(title);
        }


    }



    private void setImmersionStatus() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {

        }
    }
}
